<template>
  <div class="profile-page">
    <div class="profile-container">
      <div class="profile-header">
        <h1 class="profile-title">个人中心</h1>
        <p class="profile-subtitle">管理您的个人信息和账户设置</p>
      </div>
      


      <!-- 用户信息卡片 -->
      <div class="user-info-card">
        <div class="user-avatar-section">
          <div class="avatar-wrapper">
            <img 
              :src="getAvatarUrl(userInfo?.avatar) || '/default-avatar.png'" 
              alt="头像" 
              class="user-avatar"
            >
            <div class="avatar-overlay">
              <i class="fas fa-camera"></i>
            </div>
          </div>
        </div>
        <div class="user-details">
          <h2 class="user-name">{{ userInfo?.nickname || userInfo?.username }}</h2>
          <div class="user-meta">
            <span class="meta-item">
              <i class="fas fa-user-tag"></i>
              {{ userInfo?.role === 'USER' ? '普通用户' : userInfo?.role === 'ADMIN' ? '管理员' : userInfo?.role }}
            </span>
            <span class="meta-item">
              <i class="fas fa-id-badge"></i>
              ID: {{ userInfo?.id }}
            </span>
          </div>
        </div>
      </div>

      <!-- 权限提示 -->
      <div v-if="!canModify" class="permission-notice">
        <div class="notice-content">
          <i class="fas fa-info-circle notice-icon"></i>
          <div class="notice-text">
            <p>管理员账户不支持修改个人信息</p>
          </div>
        </div>
      </div>

      <!-- 功能选项卡 -->
      <div v-if="canModify" class="tabs-container">
        <div class="tabs-wrapper">
          <button 
            @click="activeTab = 'avatar'"
            :class="[
              'tab-button',
              activeTab === 'avatar' ? 'tab-active' : 'tab-inactive'
            ]"
          >
            <i class="fas fa-image tab-icon"></i>
            修改头像
          </button>
          <button 
            @click="activeTab = 'nickname'"
            :class="[
              'tab-button',
              activeTab === 'nickname' ? 'tab-active' : 'tab-inactive'
            ]"
          >
            <i class="fas fa-edit tab-icon"></i>
            修改昵称
          </button>
          <button 
            @click="activeTab = 'password'"
            :class="[
              'tab-button',
              activeTab === 'password' ? 'tab-active' : 'tab-inactive'
            ]"
          >
            <i class="fas fa-lock tab-icon"></i>
            修改密码
          </button>
        </div>
      </div>

      <!-- 修改头像 -->
      <div v-if="activeTab === 'avatar' && canModify" class="content-card">
        <div class="card-header">
          <h3 class="card-title">
            <i class="fas fa-image"></i>
            修改头像
          </h3>
          <p class="card-description">上传新的头像图片，支持 JPG、PNG 格式</p>
        </div>
        
        <div class="avatar-upload-section">

          
          <div class="avatar-preview">
            <img 
              :src="previewAvatar || getAvatarUrl(userInfo?.avatar) || '/default-avatar.png'" 
              alt="头像预览" 
              class="preview-image"
            >
            <div class="preview-overlay">
              <i class="fas fa-camera"></i>
            </div>
          </div>
          
          <div class="upload-controls">
            <input 
              ref="fileInput"
              type="file" 
              accept="image/*" 
              @change="handleFileSelect"
              class="hidden"
            >
            <button 
              @click="$refs.fileInput.click()"
              class="btn btn-outline"
            >
              <i class="fas fa-folder-open"></i>
              选择图片
            </button>
            <button 
              @click="uploadAvatar"
              :disabled="!selectedFile || uploading"
              class="btn btn-primary"
            >
              <i class="fas fa-upload"></i>
              {{ uploading ? '上传中...' : '上传头像' }}
            </button>
          </div>
        </div>
        
        <div class="upload-tips">
          <div class="tip-item">
            <i class="fas fa-info-circle"></i>
            <span>文件大小不超过 10MB</span>
          </div>
          <div class="tip-item">
            <i class="fas fa-check-circle"></i>
            <span>推荐尺寸：200x200 像素</span>
          </div>
        </div>
      </div>

      <!-- 修改昵称 -->
      <div v-if="activeTab === 'nickname' && canModify" class="content-card">
        <div class="card-header">
          <h3 class="card-title">
            <i class="fas fa-edit"></i>
            修改昵称
          </h3>
          <p class="card-description">设置一个新的显示昵称，最多20个字符</p>
        </div>
        
        <form @submit.prevent="updateUserNickname" class="form-container">
          <div class="form-group">
            <label class="form-label">
              <i class="fas fa-user"></i>
              新昵称
            </label>
            <input 
              v-model="nicknameForm.nickname"
              type="text" 
              required
              maxlength="20"
              class="form-input"
              placeholder="请输入新昵称"
            >
            <div class="input-hint">
              <span>{{ nicknameForm.nickname.length }}/20 字符</span>
            </div>
          </div>
          
          <div class="form-actions">
            <button 
              type="submit"
              :disabled="nicknameLoading || !nicknameForm.nickname.trim()"
              class="btn btn-primary btn-full"
            >
              <i class="fas fa-save"></i>
              {{ nicknameLoading ? '更新中...' : '更新昵称' }}
            </button>
          </div>
        </form>
      </div>

      <!-- 修改密码 -->
      <div v-if="activeTab === 'password' && canModify" class="content-card">
        <div class="card-header">
          <h3 class="card-title">
            <i class="fas fa-lock"></i>
            修改密码
          </h3>
          <p class="card-description">为了账户安全，请设置一个强密码</p>
        </div>
        
        <form @submit.prevent="updateUserPassword" class="form-container">
          <div class="form-group">
            <label class="form-label">
              <i class="fas fa-key"></i>
              当前密码
            </label>
            <input 
              v-model="passwordForm.currentPassword"
              type="password" 
              required
              class="form-input"
              placeholder="请输入当前密码"
            >
          </div>
          
          <div class="form-group">
            <label class="form-label">
              <i class="fas fa-lock"></i>
              新密码
            </label>
            <input 
              v-model="passwordForm.newPassword"
              type="password" 
              required
              minlength="6"
              class="form-input"
              placeholder="请输入新密码（至少6位）"
            >
          </div>
          
          <div class="form-group">
            <label class="form-label">
              <i class="fas fa-check-circle"></i>
              确认新密码
            </label>
            <input 
              v-model="passwordForm.confirmPassword"
              type="password" 
              required
              class="form-input"
              placeholder="请再次输入新密码"
            >
            <div class="input-hint" v-if="passwordForm.newPassword && passwordForm.confirmPassword">
              <span :class="passwordForm.newPassword === passwordForm.confirmPassword ? 'text-green-600' : 'text-red-600'">
                <i :class="passwordForm.newPassword === passwordForm.confirmPassword ? 'fas fa-check' : 'fas fa-times'"></i>
                {{ passwordForm.newPassword === passwordForm.confirmPassword ? '密码匹配' : '密码不匹配' }}
              </span>
            </div>
          </div>
          
          <div class="form-actions">
            <button 
              type="submit"
              :disabled="passwordLoading || !isPasswordFormValid"
              class="btn btn-primary btn-full"
            >
              <i class="fas fa-save"></i>
              {{ passwordLoading ? '更新中...' : '更新密码' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import * as userApi from '../api/userApi'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

// 权限控制 - 只有普通用户才能修改信息
const canModify = computed(() => {
  return userInfo.value?.role === 'USER'
})

// 选项卡状态
const activeTab = ref('avatar')

// 头像相关
const selectedFile = ref(null)
const previewAvatar = ref('')
const uploading = ref(false)

// 昵称表单
const nicknameForm = ref({
  nickname: ''
})
const nicknameLoading = ref(false)

// 密码表单
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const passwordLoading = ref(false)

// 密码表单验证
const isPasswordFormValid = computed(() => {
  return passwordForm.value.currentPassword && 
         passwordForm.value.newPassword && 
         passwordForm.value.confirmPassword &&
         passwordForm.value.newPassword === passwordForm.value.confirmPassword &&
         passwordForm.value.newPassword.length >= 6
})

// 获取头像URL
const getAvatarUrl = (avatar) => {
  if (!avatar) {
    return null
  }
  
  if (avatar.startsWith('http')) {
    return avatar
  }
  
  // 从avatar路径中提取文件名
  let filename = avatar
  
  // 如果是完整路径，提取文件名部分
  if (avatar.includes('/')) {
    const parts = avatar.split('/')
    filename = parts[parts.length - 1]
  }
  
  // 使用StaticResourceController提供的/js/avatars/{filename}端点
  return `http://localhost:8980/js/avatars/${filename}`
}

// 处理文件选择
const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      ElMessage.warning('请选择图片文件')
      return
    }
    
    // 验证文件大小（2MB）
    if (file.size > 10 * 1024 * 1024) {
      ElMessage.warning('文件大小不能超过10MB')
      return
    }
    
    selectedFile.value = file
    
    // 创建预览
    const reader = new FileReader()
    reader.onload = (e) => {
      previewAvatar.value = e.target.result
    }
    reader.readAsDataURL(file)
  }
}

// 上传头像
const uploadAvatar = async () => {
  if (!selectedFile.value) return
  
  // 检查权限
  if (!canModify.value) {
    ElMessage.warning('管理员账户不支持修改头像')
    return
  }
  
  uploading.value = true
  try {
    // 先上传文件
    const uploadResponse = await userApi.uploadFile(selectedFile.value)
    
    // 获取头像URL，兼容不同的响应格式
    let avatarUrl
    if (uploadResponse.data && uploadResponse.data.url) {
      avatarUrl = uploadResponse.data.url
    } else if (uploadResponse.data && uploadResponse.data.data && uploadResponse.data.data.url) {
      avatarUrl = uploadResponse.data.data.url
    } else if (uploadResponse.url) {
      avatarUrl = uploadResponse.url
    } else {
      throw new Error('上传响应格式错误')
    }
    
    // 更新用户头像
    await userApi.updateAvatar({ avatarUrl: avatarUrl })
    
    // 更新本地用户信息
    const updatedUserInfo = { ...userInfo.value, avatar: avatarUrl }
    userStore.setUserInfo(updatedUserInfo)
    
    ElMessage.success('头像更新成功')
    selectedFile.value = null
    previewAvatar.value = ''
  } catch (error) {
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(`头像更新失败: ${error.response.data.message}`)
    } else {
      ElMessage.error('头像更新失败，请重试')
    }
  } finally {
    uploading.value = false
  }
}

// 更新昵称
const updateUserNickname = async () => {
  if (!nicknameForm.value.nickname.trim()) return
  
  // 检查权限
  if (!canModify.value) {
    ElMessage.warning('管理员账户不支持修改昵称')
    return
  }
  
  nicknameLoading.value = true
  try {
    await userApi.updateNickname({ nickname: nicknameForm.value.nickname })
    
    // 更新本地用户信息
    const updatedUserInfo = { ...userInfo.value, nickname: nicknameForm.value.nickname }
    userStore.setUserInfo(updatedUserInfo)
    
    ElMessage.success('昵称更新成功')
    nicknameForm.value.nickname = ''
  } catch (error) {
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(`昵称更新失败: ${error.response.data.message}`)
    } else {
      ElMessage.error('昵称更新失败，请重试')
    }
  } finally {
    nicknameLoading.value = false
  }
}

// 更新密码
const updateUserPassword = async () => {
  if (!isPasswordFormValid.value) return
  
  // 检查权限
  if (!canModify.value) {
    ElMessage.warning('管理员账户不支持修改密码')
    return
  }
  
  passwordLoading.value = true
  try {
    await userApi.changePassword({
      oldPassword: passwordForm.value.currentPassword,
      newPassword: passwordForm.value.newPassword
    })
    
    ElMessage.success('密码更新成功')
    passwordForm.value = {
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  } catch (error) {
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(`密码更新失败: ${error.response.data.message}`)
    } else {
      ElMessage.error('密码更新失败，请检查当前密码是否正确')
    }
  } finally {
    passwordLoading.value = false
  }
}



// 初始化
onMounted(() => {
  if (userInfo.value?.nickname) {
    nicknameForm.value.nickname = userInfo.value.nickname
  }
})
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 2rem 0;
}

.profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 1rem;
}

.profile-header {
  text-align: center;
  margin-bottom: 2rem;
  color: white;
}

.profile-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.profile-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 0;
}

.user-info-card {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  margin-bottom: 2rem;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 2rem;
}

.user-avatar-section {
  flex-shrink: 0;
}

.avatar-wrapper {
  position: relative;
  width: 100px;
  height: 100px;
}

.user-avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #f3f4f6;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  color: white;
  font-size: 1.5rem;
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 1.8rem;
  font-weight: 600;
  margin: 0 0 1rem 0;
  color: #1f2937;
}

.user-meta {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #6b7280;
  font-size: 0.9rem;
}

.meta-item i {
  width: 16px;
  color: #9ca3af;
}

.permission-notice {
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  border: 2px solid #f59e0b;
  border-radius: 1rem;
  padding: 2rem;
  margin-bottom: 2rem;
  box-shadow: 0 4px 12px rgba(245, 158, 11, 0.2);
}

.notice-content {
  display: flex;
  align-items: center;
  gap: 1.5rem;
}

.notice-icon {
  font-size: 2rem;
  color: #f59e0b;
  flex-shrink: 0;
}

.notice-text h3 {
  margin: 0 0 0.5rem 0;
  color: #92400e;
  font-size: 1.2rem;
  font-weight: 600;
}

.notice-text p {
  margin: 0;
  color: #a16207;
  line-height: 1.5;
}

.tabs-container {
  margin-bottom: 2rem;
}

.tabs-wrapper {
  display: flex;
  background: white;
  border-radius: 0.75rem;
  padding: 0.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  gap: 0.5rem;
}

.tab-button {
  flex: 1;
  padding: 1rem;
  border: none;
  border-radius: 0.5rem;
  font-weight: 500;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  cursor: pointer;
}

.tab-active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.tab-inactive {
  background: transparent;
  color: #6b7280;
}

.tab-inactive:hover {
  background: #f9fafb;
  color: #374151;
}

.tab-icon {
  font-size: 1rem;
}

.content-card {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.card-header {
  margin-bottom: 2rem;
  text-align: center;
}

.card-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 0.5rem 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.card-title i {
  color: #667eea;
}

.card-description {
  color: #6b7280;
  margin: 0;
}

.avatar-upload-section {
  display: flex;
  align-items: center;
  gap: 2rem;
  margin-bottom: 2rem;
}

.avatar-preview {
  position: relative;
  width: 120px;
  height: 120px;
  flex-shrink: 0;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #f3f4f6;
}

.preview-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  color: white;
  font-size: 1.5rem;
}

.avatar-preview:hover .preview-overlay {
  opacity: 1;
}

.upload-controls {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  flex: 1;
}

.hidden {
  display: none;
}

.btn {
  padding: 0.75rem 1.5rem;
  border-radius: 0.5rem;
  font-weight: 500;
  transition: all 0.3s;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  font-size: 0.9rem;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.btn-outline {
  background: transparent;
  color: #667eea;
  border: 2px solid #667eea;
}

.btn-outline:hover:not(:disabled) {
  background: #667eea;
  color: white;
}

.btn-full {
  width: 100%;
}

.upload-tips {
  display: flex;
  gap: 2rem;
  justify-content: center;
  flex-wrap: wrap;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #6b7280;
  font-size: 0.9rem;
}

.tip-item i {
  color: #10b981;
}

.form-container {
  max-width: 400px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-weight: 500;
  color: #374151;
  margin-bottom: 0.5rem;
}

.form-label i {
  color: #667eea;
  width: 16px;
}

.form-input {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 2px solid #e5e7eb;
  border-radius: 0.5rem;
  font-size: 1rem;
  transition: all 0.3s;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.input-hint {
  margin-top: 0.5rem;
  font-size: 0.8rem;
  color: #6b7280;
  text-align: right;
}

.text-green-600 {
  color: #10b981;
}

.text-red-600 {
  color: #ef4444;
}

.form-actions {
  margin-top: 2rem;
}

@media (max-width: 768px) {
  .profile-container {
    padding: 0 1rem;
  }
  
  .profile-title {
    font-size: 2rem;
  }
  
  .user-info-card {
    flex-direction: column;
    text-align: center;
    gap: 1rem;
  }
  
  .permission-notice {
    padding: 1.5rem;
  }
  
  .notice-content {
    flex-direction: column;
    text-align: center;
    gap: 1rem;
  }
  
  .notice-icon {
    font-size: 1.5rem;
  }
  
  .tabs-wrapper {
    flex-direction: column;
  }
  
  .avatar-upload-section {
    flex-direction: column;
    gap: 1rem;
  }
  
  .upload-tips {
    flex-direction: column;
    gap: 1rem;
  }
}
</style>